package com.zztl.infiniteBand.ui.view

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.View
import com.zztl.infiniteBand.R

class ScrollImageView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {

    private var resource: Int = 0
    private var speed: Float = 0.toFloat()
    private var bitmapWidth: Int = 0
    var offset = 0f
    private var bitmap: Bitmap? = null
    private var isStarted = false

    init {
        init(context, attrs)
    }

    private fun init(context: Context, attrs: AttributeSet?) {
        val array = context.obtainStyledAttributes(attrs, R.styleable.ScrollImageView)
        resource = array.getResourceId(R.styleable.ScrollImageView_src, R.mipmap.cexueya_kapian2)
        speed = array.getDimension(R.styleable.ScrollImageView_speed, 20f)
        bitmap = BitmapFactory.decodeResource(resources, resource)
        bitmapWidth = bitmap!!.width

        array.recycle()

    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val w = View.MeasureSpec.getSize(widthMeasureSpec)
        val h = View.MeasureSpec.getSize(heightMeasureSpec)
        setMeasuredDimension(w, h)
    }

    override fun onDraw(canvas: Canvas?) {
        if (canvas == null) {
            return
        }
        //        canvas.getClipBounds(clipBounds);
        if (offset < -bitmapWidth) {
            offset += Math.abs(offset) / bitmapWidth * bitmapWidth
        }
        var left = offset
        while (left < measuredWidth) {
            canvas.drawBitmap(bitmap!!, getBitmapLeft(bitmapWidth.toFloat(), left), top.toFloat(), null)
            left += bitmapWidth.toFloat()
        }
        start()
    }

    private fun getBitmapLeft(bitmapWidth: Float, left: Float): Float {
        return if (speed < 0) {
            measuredWidth.toFloat() - bitmapWidth - left
        } else {
            left
        }
    }

    fun start() {
        if (!isStarted) {
//            isStarted = true
            return
        }
        offset -= Math.abs(speed)
        postInvalidateOnAnimation()
    }

    fun setStart(start:Boolean){
        isStarted=start
        invalidate()
    }

    fun stop() {
        if (isStarted) {
            isStarted = false
            invalidate()
        }
    }
}//    private Rect clipBounds = new Rect();
